<template>
    <ContentField v-if="is_show">
        <div class="row justify-content-md-center">
            <div class="col-3 ">
                <form @submit.prevent="login">
                    <div>
                        <label for="username" class="form-label">用户名</label>
                        <input v-model="username" type="text" class="form-control" id="username" placeholder="请输入用户名">
                    </div>
                    <div>
                        <label for="password" class="form-label">密码</label>
                        <input v-model="password" type="password" class="form-control" id="password"
                            placeholder="请输入密码">
                    </div>
                    <div class="error_message">{{ error_message }}</div>
                    <div>
                        <button type="submit" class="btn btn-primary">登录</button>
                    </div>

                </form>
            </div>
        </div>
    </ContentField>
</template>

<script>
import ContentField from '../../../components/ContentField.vue'
import { useStore } from 'vuex';
import { ref } from 'vue';
import router from '../../../router/index';
import store from '@/store';

export default {
    components: {
        ContentField
    },
    setup() {
        let is_show = ref(false);
        const stroe = useStore();
        let username = ref('');
        let password = ref("");
        let error_message = ref("");
        store.commit("updateIsRecord", false);
        const jwt_token = localStorage.getItem("jwt_token");
        if (jwt_token) {

            store.commit("updateToken", jwt_token);
            store.dispatch("getInfo", {
                success() {
                    router.push({ name: 'home' });
                    is_show.value = false;
                },
                error() {
                    is_show.value = true;
                }
            })
        } else {
            is_show.value = true;
        }

        const login = () => {
            stroe.dispatch("login", {
                username: username.value,
                password: password.value,
                success() {
                    stroe.dispatch("getInfo", {
                        success() {
                            router.push({ name: 'home' });
                        },
                        error() {

                        }
                    })
                },
                error() {
                    error_message.value = "用户名或密码错误";
                }
            })
        }

        return {
            username,
            password,
            error_message,
            login,
            is_show,
        }
    }
}
</script>

<style scoped>
button {
    width: 100%
}

div {
    margin-bottom: 10px;
}

div.error_message {
    color: red;
}
</style>